/**
 * 
 */
package partitioning;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author puneet
 * 
 */
public class PartitionController {
	private static List<GraphPartition> partitions;

	public static void registerPartition(GraphPartition partition) {
		if (partition == null) {
			return;
		}
		if (partitions == null) {
			partitions = new ArrayList<GraphPartition>();
		}
		partitions.add(partition);
	}
	
	public static void broadcastMessage(final String message) {
		for(GraphPartition partition:partitions) {
			final GraphPartition thisPartition = partition;
			if(!partition.isLocal()) {
				Thread t = new Thread() {
					public void run() {
						retryloop:for(int i=0;i<3;i++) {
							try {
								Socket socket = new Socket(thisPartition.getHost(),thisPartition.getPort());
								BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
								bw.write(message+"\n");
								bw.flush();
								bw.close();
								socket.close();
								break retryloop;
							} catch (UnknownHostException e) {
								System.err.println("Exception for:" + thisPartition + " retry: "+i);
								e.printStackTrace();
								
							} catch (IOException e) {
								System.err.println("Exception for:" + thisPartition+" retry: "+i);
								e.printStackTrace();
							}
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
				};
				t.start();
				try {
					t.join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	
}
